package com.gz.thread.juc;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 测试Lock锁
 */
public class Test {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();


        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
    }
}


class Data{
    private int number;

    Lock lock = new ReentrantLock();

    Condition condition = lock.newCondition();

    public void incr() throws InterruptedException {
        lock.lock();
        while (number > 0) {
            condition.await();
        }
        number++;
        System.out.println(Thread.currentThread().getName()+"===>"+number);
        condition.signalAll();
        lock.unlock();
    }


    public void decr() throws InterruptedException {
        lock.lock();
        while (number == 0) {  //使用if判断会造成虚拟唤醒的情况
            condition.await();
        }
        number--;
        System.out.println(Thread.currentThread().getName()+"===>"+number);
        condition.signalAll();
        lock.unlock();
    }
}
